package cn.cimoc.handler;

import cn.cimoc.constant.ConstantPool;
import cn.cimoc.model.vo.ResultVO;
import cn.cimoc.util.CommonUtils;
import cn.cimoc.util.RedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.cimoc.constant.ErrorEnum;
import cn.cimoc.service.JwtService;
import cn.cimoc.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author LGZ
 * @date 2021/11/20 16:42
 * <p>
 * 登录成功时做的处理
 */
public class JsonLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    RedisUtils redisUtils;

    private JwtService jwtService;

    public JsonLoginSuccessHandler(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = jwtService.saveUserLoginInfo((UserDetails) authentication.getPrincipal());
        // 因为前端没有带token，那只能我自己模拟了
        redisUtils.set(ConstantPool.FAQ, token);
        response.setHeader(JwtUtils.TOKEN_HEADER, JwtUtils.TOKEN_PREFIX + token);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        HashMap<String, String> map = new HashMap<>();
        map.put("avatar", jwtService.getAvatar(token));
        ResultVO reason = CommonUtils.ajaxReturn(map);
        response.getWriter().write(new ObjectMapper().writeValueAsString(reason));
    }
}
